package com.ckm.context;

import org.springframework.core.NamedThreadLocal;

import java.util.ArrayDeque;
import java.util.Deque;

public final class DynamicMongoContextHolder {

    private static final ThreadLocal<Deque<String>> CONTEXT_HOLDER = new InheritableThreadLocal<>() {
        @Override
        protected Deque<String> initialValue() {
            return new ArrayDeque<>();
        }
    };

    public static void setMongoContext(String key){
        CONTEXT_HOLDER.get().push(key);
    }

    public static void clearMongoContext(){
        CONTEXT_HOLDER.get().remove();
    }

    public static String getMongoContext(){
        return CONTEXT_HOLDER.get().peek();
    }

    public static void pollMongoContext(){
        Deque<String> deque = CONTEXT_HOLDER.get();
        deque.poll();
        if (deque.isEmpty()){
            CONTEXT_HOLDER.remove();
        }
    }
}
